package com.adjaisd.scarecrow.controller;

import com.adjaisd.scarecrow.common.result.Result;
import com.adjaisd.scarecrow.common.utils.jwt.JwtUtils;
import com.adjaisd.scarecrow.dto.HeapPoint;
import com.adjaisd.scarecrow.dto.TrendPoint;
import com.adjaisd.scarecrow.entity.Device;
import com.adjaisd.scarecrow.service.DeviceService;
import com.adjaisd.scarecrow.service.ReportService;
import com.adjaisd.scarecrow.vo.HeapPointVO;
import com.adjaisd.scarecrow.vo.LineVO;
import com.adjaisd.scarecrow.vo.PieVO;
import com.google.common.collect.Lists;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/report")
public class ReportController {

    @Autowired
    ReportService reportService;

    @ApiOperation(value = "各种状态设备数")
    @RequestMapping(value = "/chart", method = RequestMethod.GET)
    public Result getDeviceStatusChart(HttpServletRequest request) {
        String token = request.getHeader("X-token");
        Claims claims = JwtUtils.getMembers(token);
        long userId = Long.parseLong(claims.get("id").toString());

        List<PieVO> list = reportService.getDeviceStatusChart(userId);
        return Result.succ().code(200).data("list", list).message("查询设备数成功");
    }

    // 获取告警趋势
    @ApiOperation(value = "获取告警趋势")
    @ApiImplicitParam(name = "map", required = true, value = "趋势信息表", paramType = "body", dataType = "json")
    @RequestMapping(value = "/alarm-trend", method = RequestMethod.POST)
    @ResponseBody
    public Result getAlarmTrend(HttpServletRequest request, @RequestBody Map<String, String> map) {
        String token = request.getHeader("X-token");
        Claims claims = JwtUtils.getMembers(token);
        Long userId = Long.parseLong(claims.get("id").toString());

        try {
            String beg = map.get("beg");
            String end = map.get("end");
            int type = Integer.parseInt(map.get("type"));
            List<TrendPoint> trendPointList = reportService.getAlarmTrend(userId, beg, end, type);
            if (trendPointList == null)
                return Result.fail().code(400).message("参数错误");
            LineVO lineVO = new LineVO();
            lineVO.setXData(Lists.newArrayList());
            lineVO.setSeries(Lists.newArrayList());
            trendPointList.forEach(t -> {
                lineVO.getXData().add(formatTime(t.getTime(), type));
                lineVO.getSeries().add(t.getPointValue().longValue());
            });
            return Result.succ().code(200).data("trend", lineVO).message("查询报警趋势成功");
        } catch (Exception e) {
            System.out.println(e);
            return Result.fail().code(400).message("参数错误");
        }
    }

    @Autowired
    DeviceService deviceService;

    @ApiOperation(value = "获取最多报警设备")
    @ApiImplicitParam(name = "map", required = true, value = "趋势信息表", paramType = "body", dataType = "json")
    @RequestMapping(value = "/top10Alarm", method = RequestMethod.POST)
    @ResponseBody
    public Result getTop10Alarm(HttpServletRequest request, @RequestBody Map<String, String> map) {
        String token = request.getHeader("X-token");
        Claims claims = JwtUtils.getMembers(token);
        Long userId = Long.parseLong(claims.get("id").toString());

        try {
            String beg = map.get("beg");
            String end = map.get("end");
            List<HeapPoint> topList = reportService.getTop10Alarm(userId, beg, end);
            // System.out.println("topList" + topList);
            if (topList == null)
                return Result.fail().code(400).message("暂无报警");
            List<HeapPointVO> list = new LinkedList<>();
            for (HeapPoint heapPoint : topList) {
                Device deviceByID = deviceService.getDeviceByID(Long.valueOf(heapPoint.getDeviceId()));
                if (deviceByID==null) continue;
                HeapPointVO heapPointVO = new HeapPointVO();

                BeanUtils.copyProperties(heapPoint, heapPointVO);
                heapPointVO.setNumber(deviceByID.getNumber() + "");
                heapPointVO.setDeviceName(deviceByID.getName());
                list.add(heapPointVO);
            }
            return Result.succ().code(200).data("top", list).message("查询最多报警设备成功");
        } catch (Exception e) {
            System.out.println(e);
            return Result.fail().code(400).message("参数错误");
        }
    }


    private String formatTime(String time, int type) {
        LocalDateTime localDateTime = LocalDateTime.parse(time, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
        if (type == 1) return localDateTime.getMinute() + "";
        else if (type == 2) return localDateTime.getHour() + "";
        else if (type == 3) return localDateTime.getMonthValue() + "月" + localDateTime.getDayOfMonth() + "日";
        else return time;
    }
}
